<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="export2Excel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>

        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" width="50" align="center" />
          <el-table-column label="头像" sortable="" prop="staffPhoto" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/75f0283960d319b346f9a8ff0c875757.png')" :src="row.staffPhoto" alt="" class="avatar">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" align="center" />
          <el-table-column label="工号" sortable="" prop="workNumber" align="center" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" align="center" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" align="center" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" align="center">
            <template #default="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" align="center">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280" align="center">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="pageSetting.size" :total="total" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>
    <addEmployee :show-dialog="showDialog" />
    <assignRole ref="assignRole" :user-id="userId" :show-role-dialog.sync="isShowDialog" />
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import addEmployee from '@/views/employees/components/add-employee.vue'
import assignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, assignRole },
  data() {
    return {
      pageSetting: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      showDialog: false,
      isShowDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {

    async getEmployee() {
      const { rows, total } = await getEmployeeList(this.pageSetting)
      this.employeeList = rows.map(user => {
        const enableState = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || enableState

        }
      })
      this.total = total
    },
    changePage(newpage) {
      this.pageSetting.page = newpage
      this.getEmployee()
    },
    formatEmployment(row, column, cellVal) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellVal)
      return obj ? obj.value : '未知'
    },
    async export2Excel() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total
      })
      console.log(102, rows)
      const header = ['姓名', '工号', '聘用形式', '入职日期', '转正日期']
      const data = rows.map(item => {
        return this.objToArr(item)
      })
      // console.log(107, data)
      export_json_to_excel({
        header,
        data
      })
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     // 生成excel文件的方法
      //     ['rose', 19, '女'],
      //     ['jack', 16, '男'],
      //     ['tom', 20, '男'],
      //     ['jerry', 12, '男']
      //   ]
      // })
    },
    objToArr(objUser) {
      const arrUser = []
      // 中间转换
      const zidian = {
        '姓名': 'username',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime'
      }
      for (const key in zidian) {
        const enkey = zidian[key]
        const value = objUser[enkey]

        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          arrUser.push(formatDate(value))
        } else if (enkey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(item => item.id === value)
          arrUser.push(obj ? obj.value : '未知')
        } else {
          arrUser.push(value)
        }
      }
      console.log(145, arrUser)
      return arrUser
    },
    async del(id) {
      await this.$confirm('是否删除')
      await delEmployee(id)
      this.$message.success('删除成功')
      this.getEmployee()
    },
    assign(id) {
      this.userId = id
      this.isShowDialog = true
      this.$refs.assignRole.getUserDetail(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 180px;
  height: 120px;
  object-fit: cover;
}
</style>
